package springbook.user.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import springbook.user.domain.User;

public class UserDao {
	ConnectionMaker connectionMaker = null;
	
	public UserDao(ConnectionMaker connectionMaker) {
		System.out.println(this.getClass().getName()+".UserDao()");
		this.connectionMaker = connectionMaker;
	}
	public void add(User user) throws ClassNotFoundException, SQLException{
		System.out.println(this.getClass().getName()+".add()");
		Connection c = connectionMaker.makeConnection();
		PreparedStatement ps = c.prepareStatement("insert into TOBY_USERS(id, name, password) values(?,?,?)");
		ps.setString(1, user.getId());
		ps.setString(2, user.getName());
		ps.setString(3, user.getPassword());
		
		ps.executeUpdate();
		
		ps.close();
		c.close();
		
	}
	public void del(User user) throws ClassNotFoundException, SQLException{
		System.out.println(this.getClass().getName()+".del()");
		Connection c = connectionMaker.makeConnection();
		PreparedStatement ps = c.prepareStatement("delete from TOBY_USERS where id = ?");
		ps.setString(1, user.getId());
		
		ps.executeUpdate();
		
		ps.close();
		c.close();
		
	}

	public User get(String id) throws ClassNotFoundException, SQLException{
		System.out.println(this.getClass().getName()+".get()");
		Connection c = connectionMaker.makeConnection();
		PreparedStatement ps = c.prepareStatement("select * from TOBY_USERS where id = ?");
		ps.setString(1, id);
		
		ResultSet rs = ps.executeQuery();
		rs.next();
		User user = new User();
		user.setId(rs.getString("id"));
		user.setName(rs.getString("name"));
		user.setPassword(rs.getString("password"));
		
		rs.close();
		ps.close();
		c.close();
		
		return user;
		
	}
	
	
}
